// 获取用户信息函数（保持兼容性）
function getUserInfo() {
    return Utils.getUserInfo();
}

// 学科管理组件
function SubjectManagement() {
    // 初始化空数组，将从API加载数据
    const [subjects, setSubjects] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [searchTerm, setSearchTerm] = React.useState('');
    const [currentPage, setCurrentPage] = React.useState(1);
    const [itemsPerPage, setItemsPerPage] = React.useState(10);
    const [totalCount, setTotalCount] = React.useState(0);
    const userInfo = getUserInfo();
    
    // 模拟数据，当API不可用时使用
    const mockSubjects = [
        { id: 1, name: '数学', code: 'MATH', description: '高中数学课程', credit: 5, status: 'active' },
        { id: 2, name: '语文', code: 'CHINESE', description: '高中语文课程', credit: 5, status: 'active' },
        { id: 3, name: '英语', code: 'ENGLISH', description: '高中英语课程', credit: 5, status: 'active' },
        { id: 4, name: '物理', code: 'PHYSICS', description: '高中物理课程', credit: 4, status: 'active' },
        { id: 5, name: '化学', code: 'CHEMISTRY', description: '高中化学课程', credit: 4, status: 'inactive' }
    ];
    
    // 创建一个ref来跟踪组件的挂载状态
    const isMountedRef = React.useRef(true);
    
    // 组件卸载时设置isMounted为false
    React.useEffect(() => {
        return () => {
            isMountedRef.current = false;
        };
    }, []);
    
    // 从API获取学科数据 - 添加isMounted检查以避免内存泄漏
    const fetchSubjects = React.useCallback(async (page = 1, search = '') => {
        setLoading(true);
        try {
            // 构建API请求URL，包含分页和搜索参数
            const url = `/chm/api/subjects?page=${page}&pageSize=${itemsPerPage}${search ? `&search=${encodeURIComponent(search)}` : ''}`;
            
            // 尝试从API获取数据
            const response = await Utils.fetchData(url);
            
            // 检查组件是否仍然挂载
            if (!isMountedRef.current) return;
            
            // 检查response格式
            if (response && response.status === 0) {
                // 根据API实际返回格式，从response.data.rows获取学科数据数组，从response.data.count获取总数
                if (response.data && response.data.rows && Array.isArray(response.data.rows)) {
                    setSubjects(response.data.rows);
                    setTotalCount(response.data.count || response.data.rows.length);
                    console.log('从API加载学科数据成功');
                } else {
                    console.warn('API数据格式不正确，使用模拟数据');
                    setSubjects(mockSubjects);
                    setTotalCount(mockSubjects.length);
                }
            } else {
                // API返回空数据或状态码不为0时使用模拟数据
                console.warn('API返回数据错误或状态码不为0，使用模拟数据');
                setSubjects(mockSubjects);
                setTotalCount(mockSubjects.length);
            }
        } catch (error) {
            // 检查组件是否仍然挂载
            if (!isMountedRef.current) return;
            
            // API调用失败时使用模拟数据
            console.error('从API加载学科数据失败，使用模拟数据:', error);
            setSubjects(mockSubjects);
            setTotalCount(mockSubjects.length);
        } finally {
            // 检查组件是否仍然挂载
            if (isMountedRef.current) {
                setLoading(false);
            }
        }
    }, [itemsPerPage]);
    
    // 组件挂载时获取数据
    React.useEffect(() => {
        fetchSubjects(currentPage, searchTerm);
    }, [fetchSubjects, currentPage, searchTerm]);

    // 分页计算 - 当从API加载数据时，totalCount由API提供
    const totalPages = Math.ceil(totalCount / itemsPerPage);
    
    // 过滤学科数据（客户端过滤）- 确保subjects是数组
    const filteredSubjects = Array.isArray(subjects) ? subjects.filter(subject => 
        subject.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        subject.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
        subject.description.toLowerCase().includes(searchTerm.toLowerCase())
    ) : [];

    // 当前页显示的数据
    const currentSubjects = filteredSubjects.slice(0, itemsPerPage);

    // 处理搜索
    const handleSearch = (e) => {
        setSearchTerm(e.target.value);
        setCurrentPage(1);
    };

    // 处理分页
    const handlePageChange = (page) => {
        setCurrentPage(page);
    };
    
    // 处理每页条数变化
    const handleItemsPerPageChange = (newItemsPerPage) => {
        setItemsPerPage(newItemsPerPage);
        setCurrentPage(1); // 重置到第1页
    };

    // 新增学科
    const handleAddSubject = () => {
        // 模拟新增学科数据
        const newSubject = {
            id: Date.now(), // 临时ID
            name: '新学科' + Date.now().toString().slice(-4),
            code: 'SUB' + Date.now().toString().slice(-6).toUpperCase(),
            description: '新学科描述',
            credit: 3,
            status: 'active',
            createTime: new Date().toISOString()
        };
        
        // 调用API新增学科
        Utils.createItem('/chm/api/subjects', newSubject)
            .then(() => {
                Utils.showAlert('学科新增成功', 'success');
                fetchSubjects(currentPage, searchTerm); // 重新加载数据
            })
            .catch(error => {
                console.error('新增学科失败:', error);
                Utils.showAlert('学科新增失败', 'error');
            });
    };

    // 导入学科
    const handleImportSubjects = () => {
        Utils.showAlert('导入学科功能开发中...', 'info');
    };

    // 编辑学科
    const handleEditSubject = (subject) => {
        // 模拟编辑后的数据
        const updatedSubject = {
            ...subject,
            name: subject.name + '(编辑)', // 简单修改用于演示
            updateTime: new Date().toISOString()
        };
        
        // 调用API更新学科信息
        Utils.updateItem(`/chm/api/subjects/${subject.id}`, updatedSubject)
            .then(() => {
                Utils.showAlert('学科信息更新成功', 'success');
                fetchSubjects(currentPage, searchTerm); // 重新加载数据
            })
            .catch(error => {
                console.error('更新学科信息失败:', error);
                Utils.showAlert('学科信息更新失败', 'error');
            });
    };

    // 删除学科
    const handleDeleteSubject = (subject) => {
        if (confirm(`确定要删除学科 ${subject.name} 吗？`)) {
            // 调用API删除学科
            Utils.deleteItem(`/chm/api/subjects/${subject.id}`)
                .then(() => {
                    Utils.showAlert('学科删除成功', 'success');
                    fetchSubjects(currentPage, searchTerm); // 重新加载数据
                })
                .catch(error => {
                    console.error('删除学科失败:', error);
                    Utils.showAlert('学科删除失败', 'error');
                    // 如果API调用失败但仍然需要更新界面，可以使用前端过滤
                    setSubjects(subjects.filter(s => s.id !== subject.id));
                });
        }
    };

    // 切换学科状态
    const handleToggleStatus = (subject) => {
        // 新状态
        const newStatus = subject.status === 'active' ? 'inactive' : 'active';
        
        // 先更新本地状态，提升用户体验
        setSubjects(subjects.map(s => 
            s.id === subject.id 
                ? { ...s, status: newStatus }
                : s
        ));
        
        // 调用API更新状态
        Utils.updateItem(`/chm/api/subjects/${subject.id}/status`, { status: newStatus })
            .catch(error => {
                console.error('更新学科状态失败:', error);
                Utils.showAlert('学科状态更新失败', 'error');
                // 失败时恢复原状态
                fetchSubjects(currentPage, searchTerm);
            });
    };

    // 退出登录
    const logout = () => {
        Utils.logout();
    };

    return React.createElement('div', { className: 'flex flex-col h-screen bg-background' },
        // 主内容区域
        React.createElement('div', { className: 'flex-1 overflow-auto' },
            React.createElement('div', { className: 'p-6' },
                React.createElement('div', { className: 'bg-card rounded-lg border shadow-sm' },
                    // 标题和操作按钮 - shadcn风格
                    React.createElement('div', { className: 'px-6 py-4 border-b flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4' },
                        React.createElement('div', null,
                            React.createElement('h2', { className: 'text-2xl font-bold tracking-tight text-card-foreground' }, '学科管理'),
                            React.createElement('p', { className: 'text-sm text-muted-foreground mt-1' }, '管理系统中所有学科信息')
                        ),
                        React.createElement('div', { className: 'flex flex-wrap gap-2' },
                            React.createElement('button', {
                                onClick: handleImportSubjects,
                                className: 'inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2'
                            }, '导入学科'),
                            React.createElement('button', {
                                onClick: handleAddSubject,
                                className: 'inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-primary text-primary-foreground hover:bg-primary/90 h-9 px-4 py-2'
                            }, '新增学科')
                        )
                    ),
                    
                    // 搜索栏 - shadcn风格
                    React.createElement('div', { className: 'px-6 py-4 border-b' },
                        React.createElement('div', { className: 'relative w-full max-w-md' },
                            React.createElement('input', {
                                type: 'text',
                                placeholder: '搜索学科名称、代码或描述...',
                                value: searchTerm,
                                onChange: handleSearch,
                                className: 'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50'
                            }),
                            React.createElement('div', { className: 'absolute right-3 top-1/2 transform -translate-y-1/2 text-muted-foreground' },
                                React.createElement('svg', { 
                                    className: 'w-4 h-4',
                                    fill: 'none',
                                    stroke: 'currentColor',
                                    viewBox: '0 0 24 24'
                                },
                                    React.createElement('path', {
                                        strokeLinecap: 'round',
                                        strokeLinejoin: 'round',
                                        strokeWidth: '2',
                                        d: 'M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z'
                                    })
                                )
                            )
                        )
                    ),
                    
                    // 学科列表 - shadcn风格
                    React.createElement('div', { className: 'overflow-x-auto' },
                        React.createElement('table', { className: 'w-full caption-bottom text-sm' },
                            React.createElement('thead', { className: '[&_tr]:border-b' },
                                React.createElement('tr', { className: 'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted' },
                                    React.createElement('th', { className: 'h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]' }, '学科代码'),
                                    React.createElement('th', { className: 'h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]' }, '学科名称'),
                                    React.createElement('th', { className: 'h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]' }, '学分'),
                                    React.createElement('th', { className: 'h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]' }, '描述'),
                                    React.createElement('th', { className: 'h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]' }, '状态'),
                                    React.createElement('th', { className: 'h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]' }, '操作')
                                )
                            ),
                            React.createElement('tbody', { className: '[&_tr:last-child]:border-0' },
                                currentSubjects.length > 0 ? (
                                    currentSubjects.map(subject => 
                                        React.createElement('tr', { 
                                            key: subject.id, 
                                            className: 'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted'
                                        },
                                            React.createElement('td', { className: 'p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] font-medium' }, subject.code),
                                            React.createElement('td', { className: 'p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] text-muted-foreground' }, subject.name),
                                            React.createElement('td', { className: 'p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] text-muted-foreground' }, subject.credit),
                                            React.createElement('td', { className: 'p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px] text-muted-foreground' }, subject.description),
                                            React.createElement('td', { className: 'p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]' },
                                                React.createElement('span', { 
                                                    className: `inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 ${
                                                        subject.status === 'active' 
                                                            ? 'border-transparent bg-green-100 text-green-800 hover:bg-green-100/80' 
                                                            : 'border-transparent bg-red-100 text-red-800 hover:bg-red-100/80'
                                                    }`
                                                }, subject.status === 'active' ? '启用' : '禁用')
                                            ),
                                            React.createElement('td', { className: 'p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]' },
                                                React.createElement('div', { className: 'flex items-center space-x-1' },
                                                    React.createElement('button', { 
                                                        onClick: () => handleEditSubject(subject),
                                                        className: 'inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-8 px-2 py-1'
                                                    }, '编辑'),
                                                    React.createElement('button', { 
                                                        onClick: () => handleToggleStatus(subject),
                                                        className: 'inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-secondary text-secondary-foreground hover:bg-secondary/80 h-8 px-2 py-1'
                                                    }, subject.status === 'active' ? '禁用' : '启用'),
                                                    React.createElement('button', { 
                                                        onClick: () => handleDeleteSubject(subject),
                                                        className: 'inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-destructive text-destructive-foreground hover:bg-destructive/90 h-8 px-2 py-1'
                                                    }, '删除')
                                                )
                                            )
                                        )
                                    )
                                ) : (
                                    React.createElement('tr', null,
                                        React.createElement('td', { 
                                            colSpan: 6, 
                                            className: 'p-8 text-center text-muted-foreground'
                                        },
                                            React.createElement('div', { className: 'flex flex-col items-center justify-center space-y-2' },
                                                React.createElement('svg', { 
                                                    className: 'w-12 h-12 text-muted-foreground/50',
                                                    fill: 'none',
                                                    stroke: 'currentColor',
                                                    viewBox: '0 0 24 24'
                                                },
                                                    React.createElement('path', {
                                                        strokeLinecap: 'round',
                                                        strokeLinejoin: 'round',
                                                        strokeWidth: '2',
                                                        d: 'M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10'
                                                    })
                                                ),
                                                React.createElement('p', { className: 'text-sm' }, '暂无学科数据')
                                            )
                                        )
                                    )
                                )
                            )
                        )
                    ),
                    
                    // 分页
                    filteredSubjects.length > 0 && Utils.Pagination({
                        currentPage: currentPage,
                        totalPages: totalPages,
                        totalCount: filteredSubjects.length,
                        itemsPerPage: itemsPerPage,
                        onPageChange: handlePageChange,
                        onItemsPerPageChange: handleItemsPerPageChange
                    })
                )
            )
        )
    );
}

// 将组件暴露到全局作用域，使其可被admin.js访问
window.SubjectManagement = SubjectManagement;